package client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author MyPC
 * @date 2018/7/4
 */

public class SimpleSocketClient {

    private Socket mSocket;
    private String serverHost;
    private int port;
    private InetSocketAddress mInetSocketAddress;
    public static final int TIME_OUT = 10 * 1000;


    public SimpleSocketClient(Builder builder) {
        this.mSocket = builder.mSocket;
        this.serverHost = builder.serverHost;
        this.port = builder.port;
        mInetSocketAddress = new InetSocketAddress(serverHost, port);
    }

    private static SimpleSocketClient socketClient;

    private SimpleSocketClient() {
        if (socketClient == null) {
            synchronized (SimpleSocketClient.class) {
                if (socketClient == null) {
                    socketClient = new SimpleSocketClient();
                }
            }
        }
    }


    public void connectServer(SocketConnectionCallBack socketConnectionCallBack) {
        boolean unReachable = unReachable(mInetSocketAddress);
        if (unReachable) {
            if (mSocket == null) {
                mSocket = new Socket();
            }
            try {
                mSocket.connect(mInetSocketAddress, TIME_OUT);
                mSocket.setSoTimeout(10000);
                mSocket.setKeepAlive(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (mSocket.isConnected()) {
                socketConnectionCallBack.onSocketConnectionSuccess(mSocket);
            } else {
                socketConnectionCallBack.onSocketConnectionError("socket is not connected,please check the server");
            }
        } else {
            socketConnectionCallBack.onSocketConnectionError("ERROR: The inetSocketAddress is  unreachable");
        }


    }


    public boolean unReachable(InetSocketAddress inetSocketAddress) {
        return inetSocketAddress.isUnresolved();
    }


    public static class Builder {
        private Socket mSocket;
        private String serverHost;
        private int port;



        public Socket getSocket() {
            return mSocket;
        }

        public Builder setSocket(Socket socket) {
            mSocket = socket;
            return this;
        }

        public String getServerHost() {
            return serverHost;
        }

        public Builder setServerHost(String serverHost) {
            this.serverHost = serverHost;
            return this;
        }

        public int getPort() {
            return port;
        }

        public Builder setPort(int port) {
            this.port = port;
            return this;
        }


        public SimpleSocketClient build() {
            return new SimpleSocketClient(this);
        }
    }
}
